#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试重构后的Agent架构
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def test_agent_factory():
    """测试Agent工厂"""
    print("=" * 60)
    print("测试Agent工厂系统")
    print("=" * 60)
    
    try:
        from core.agent_factory import get_agent_factory, list_available_agents, create_agent
        
        # 测试工厂初始化
        factory = get_agent_factory()
        print("✓ Agent工厂初始化成功")
        
        # 测试列出可用Agent
        agents = list_available_agents()
        print(f"✓ 发现 {len(agents)} 个可用Agent:")
        for agent in agents:
            print(f"  - {agent['name']}: {agent['display_name']} ({agent['type']})")
        
        # 测试创建Agent
        print("\n测试创建Agent:")
        
        # 创建对话Agent
        conversational_agent = create_agent("conversational", config_name="ai")
        if conversational_agent:
            print(f"✓ 对话Agent创建成功: {conversational_agent.name}")
        
        # 创建代码Agent
        code_agent = create_agent("code")
        if code_agent:
            print(f"✓ 代码Agent创建成功: {code_agent.name}")
            print(f"  工具数量: {len(code_agent.tools.getTools())}")
        
        return True
        
    except Exception as e:
        print(f"✗ Agent工厂测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def test_base_agents():
    """测试基础Agent类"""
    print("\n" + "=" * 60)
    print("测试基础Agent类")
    print("=" * 60)
    
    try:
        from core.base_agent import ConversationalAgent, TaskOrientedAgent
        
        # 测试对话Agent
        print("测试ConversationalAgent:")
        conv_agent = ConversationalAgent("ai")
        print(f"  名称: {conv_agent.name}")
        print(f"  版本: {conv_agent.version}")
        print(f"  描述: {conv_agent.description}")
        print(f"  工具数量: {len(conv_agent.tools.getTools())}")
        
        # 测试简单对话
        response = conv_agent.chat("你好，你是谁？", reset=True)
        print(f"  对话响应: {response[:100]}...")
        print("✓ ConversationalAgent测试通过")
        
        # 测试代码Agent
        print("\n测试TaskOrientedAgent:")
        task_agent = TaskOrientedAgent("code")
        print(f"  名称: {task_agent.name}")
        print(f"  版本: {task_agent.version}")
        print(f"  描述: {task_agent.description}")
        print("✓ TaskOrientedAgent基础测试通过")
        
        return True
        
    except Exception as e:
        print(f"✗ 基础Agent测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def test_code_agent():
    """测试代码Agent"""
    print("\n" + "=" * 60)
    print("测试代码Agent功能")
    print("=" * 60)
    
    try:
        from agents.code_agent import CodeAgent
        
        # 创建代码Agent
        code_agent = CodeAgent()
        print(f"✓ CodeAgent创建成功: {code_agent.name}")
        
        # 测试文件分析
        print("\n测试文件分析:")
        analysis = code_agent.analyze_file("agent.py")
        if analysis["success"]:
            print("✓ 文件分析成功")
            print(f"  文件: {analysis['file_path']}")
            print(f"  行数: {analysis['lines']}")
            print(f"  语言: {analysis['language']}")
            print(f"  函数: {analysis['functions']}")
            print(f"  类: {analysis['classes']}")
        else:
            print(f"✗ 文件分析失败: {analysis['error']}")
        
        # 测试代码对话
        print("\n测试代码对话:")
        response = code_agent.chat("请分析agent.py文件的结构", reset=True)
        print(f"✓ 代码对话响应: {response[:100]}...")
        
        # 测试工具执行
        print("\n测试工具执行:")
        if hasattr(code_agent, 'code_tools'):
            tools = code_agent.code_tools.getTools()
            print(f"✓ 代码工具数量: {len(tools)}")
            for tool in tools[:3]:  # 只显示前3个
                print(f"  - {tool['name']}: {tool['description'][:50]}...")
        
        return True
        
    except Exception as e:
        print(f"✗ CodeAgent测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def test_backward_compatibility():
    """测试向后兼容性"""
    print("\n" + "=" * 60)
    print("测试向后兼容性")
    print("=" * 60)
    
    try:
        # 测试原有接口
        from agent import Agent
        from codeagent import CodeAgent
        
        # 原有的Agent
        old_agent = Agent()
        print(f"✓ 原有Agent接口: {old_agent.name}")
        response = old_agent.chat("测试兼容性")
        print(f"✓ 原有Agent对话正常")
        
        # 原有的CodeAgent
        old_code_agent = CodeAgent()
        print(f"✓ 原有CodeAgent接口: {old_code_agent.name}")
        
        # 测试原有API
        old_code_agent.set_current_file("agent.py")
        print(f"✓ set_current_file API正常")
        
        return True
        
    except Exception as e:
        print(f"✗ 向后兼容性测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def test_main_program():
    """测试主程序集成"""
    print("\n" + "=" * 60)
    print("测试主程序集成")
    print("=" * 60)
    
    try:
        from shell.aishell import AiShell
        from agent import Agent
        from codeagent import CodeAgent
        
        # 初始化组件
        shell = AiShell()
        agent = Agent()
        code_agent = CodeAgent()
        
        # 设置到shell中
        shell.setAgent(agent)
        shell.setCodeAgent(code_agent)
        
        print("✓ 主程序组件初始化成功")
        print(f"✓ 普通Agent: {agent.name()}")
        print(f"✓ 代码Agent: {code_agent.name()}")
        
        # 测试模式切换
        print(f"✓ 初始模式: {shell.current_mode}")
        shell.do_code("")
        print(f"✓ 切换到代码模式: {shell.current_mode}")
        shell.do_normal("")
        print(f"✓ 切回普通模式: {shell.current_mode}")
        
        return True
        
    except Exception as e:
        print(f"✗ 主程序集成测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """主测试函数"""
    print("开始测试重构后的Agent架构...")
    
    tests = [
        ("Agent工厂系统", test_agent_factory),
        ("基础Agent类", test_base_agents),
        ("代码Agent功能", test_code_agent),
        ("向后兼容性", test_backward_compatibility),
        ("主程序集成", test_main_program)
    ]
    
    results = []
    for test_name, test_func in tests:
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"✗ {test_name} 测试异常: {str(e)}")
            results.append((test_name, False))
    
    # 总结
    print("\n" + "=" * 60)
    print("测试结果总结")
    print("=" * 60)
    
    passed = 0
    for test_name, result in results:
        status = "✓ 通过" if result else "✗ 失败"
        print(f"{test_name}: {status}")
        if result:
            passed += 1
    
    print(f"\n总计: {passed}/{len(results)} 个测试通过")
    
    if passed == len(results):
        print("🎉 所有测试通过！架构重构成功！")
        return True
    else:
        print("⚠️  部分测试失败，需要修复")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)